<template>
    <el-form ref="form" class="p-job-detail-form" :model="form" :rules="rules">
        <el-collapse v-model="activeNames" class="detail-collapse">
            <!--general-->
            <el-collapse-item
                :title="$t('lang.general')"
                name="1"
                class="genral-box"
                :class="{ readonle: readonly }"
            >
                <el-form-item :label="$t('lang.vehicleKey')" prop="vehicleKey">
                    <v-text v-if="readonly" v-model="form.vehicleKey" />
                    <!--<el-input v-else v-model="form.vehicleKey" size="small" />-->
                    <p-picker-vehicle v-else :target="true" v-model="form.vehicleKey"></p-picker-vehicle>
                </el-form-item>
                <el-form-item :label="$t('lang.priority')" prop="priority">
                    <v-text v-if="readonly" v-model="form.priority" />
                    <el-select v-else v-model="form.priority" :placeholder="$t('lang.pleaseSelect')" size="small">
                        <el-option v-for="n in 99" :key="n + 'idx'" :label="n" :value="n" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('lang.endEvent')" prop="endEvent">
                    <v-text v-if="readonly" v-model="form.endEvent" />
                    <el-select v-else v-model="form.endEvent" :placeholder="$t('lang.pleaseSelect')" size="small">
                        <el-option v-for="o in endEventOptions" :key="o + 'idx'" :label="o" :value="o" />
                    </el-select>
                </el-form-item>
                <!--</el-collapse-item>-->
                <!--&lt;!&ndash;appointment&ndash;&gt;-->
                <!--<el-collapse-item :title="$t('lang.appointment')" name="2">-->
                <el-form-item :label="$t('lang.mode')" prop="appointmentMode">
                    <v-text v-if="readonly" v-model="form.appointmentModeExt" />
                    <el-select
                        v-else
                        v-model="form.appointmentMode"
                        :placeholder="$t('lang.pleaseSelect')"
                        size="small"
                    >
                        <el-option v-for="o in modeOptions" :key="o + 'idx'" :label="o" :value="o" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('lang.time')" prop="appointmentTime">
                    <v-text v-if="readonly" v-model="form.appointmentTimeExt" />
                    <el-date-picker
                        v-else
                        v-model="form.appointmentTimeExt"
                        type="datetime"
                        :placeholder="$t('lang.pleaseSelect')"
                        default-time="9:00:00"
                        :disabled="aptTimeDisabled"
                    >
                    </el-date-picker>
                </el-form-item>

                <el-form-item :class="[{ styleLabel: true }]" :label="$t('lang.label')" prop="label">
                    <v-text v-if="readonly" v-model="form.label" />
                    <el-input v-else v-model="form.label" size="small" />
                </el-form-item>
            </el-collapse-item>
            <!--orders preview-->
            <el-collapse-item v-if="readonly" :title="$t('lang.orders')" name="3">
                <template v-for="(o, i) in form.orderList" :key="i">
                    <el-form-item class="horizontal totally">
                        <i :class="[getOrderPreviewIcon(i)]"></i>
                        <v-text :value="getOrderPreviewText(o)" />
                    </el-form-item>
                </template>
            </el-collapse-item>
            <!--orders editor-->
            <el-collapse-item v-else :title="$t('lang.orders')" name="3">
                <v-table
                    ref="vTable"
                    class="p-model-properties-detail"
                    v-model="form.orderListExt"
                    isActive
                    :columns="orderListColumns"
                    :options="orderListOptions"
                    :readonly="readonly"
                >
                    <template v-slot:field="slotProps">
                        <template v-if="slotProps.props.col.type === 'pickerPath'">
                            <p-picker-path v-model="form.orderListExt[slotProps.props.ridx][slotProps.props.cidx]" />
                        </template>
                        <template v-else-if="slotProps.props.col.type === 'pickerRange'">
                            <p-picker-range v-model="form.orderListExt[slotProps.props.ridx][slotProps.props.cidx]" />
                        </template>
                        <template v-else>
                            <v-field
                                :type="slotProps.props.col.type"
                                :idx="slotProps.props.ridx"
                                :name="slotProps.props.col.prop"
                                v-model="form.orderListExt[slotProps.props.ridx][slotProps.props.cidx]"
                                :options="orderListOptions[slotProps.props.col.prop]"
                                :validator="slotProps.props.col.validator"
                            />
                        </template>
                    </template>
                </v-table>
            </el-collapse-item>
            <!--status-->
            <el-collapse-item v-if="readonly" :title="$t('lang.status')" name="4">
                <el-form-item :label="$t('lang.progress')" prop="progress">
                    <div class="progress">
                        <div class="progressBar" :style="progressBarStyle"></div>
                        <v-text :value="form.progressExt ? form.progressExt.value : ''" />
                    </div>
                </el-form-item>
                <el-form-item :label="$t('lang.status')" prop="jobStatusDesc">
                    <v-text :value="form.jobStatusDescExt" />
                </el-form-item>
            </el-collapse-item>
            <!--properties-->
            <el-collapse-item :title="$t('lang.properties')" name="5">
                <v-table
                    ref="vTable"
                    class="p-model-properties-detail"
                    v-model="form.propertiesExt"
                    isActive
                    :columns="propertiesColumns"
                    :readonly="readonly"
                ></v-table>
            </el-collapse-item>
        </el-collapse>
        <!--buttons-->
        <p-detail-buttons :compact="compact" :submit-func="submit" :readonly="readonly"></p-detail-buttons>
    </el-form>
</template>

<script type="text/ecmascript-6">
import { JOB_END_EVENTS, JOB_MODES } from '../../../core/SYSTEM.enum.js';
import * as Chef from '../../../core/Chef.js';
import * as API from '../../../core/api.js';
import * as enums from '../../../store/status-enums.js';
import bus from '../../../utils/Eventbus.js';
import vText from '../../../utils/v-text.vue';
import vField from '../../../utils/v-field.vue';
import vTable from '../../../utils/v-table.vue';
import pDetailButtons from '../p-detail-buttons.vue';
import pPickerPath from '../../../components/p-picker-path.vue';
import pPickerRange from '../../../components/p-picker-range.vue';
import pPickerVehicle from '../../../components/p-picker-vehicle.vue';
import i18n from '../../../lang/index.js';
const $t = i18n.global.t;

export default {
    name: 'p-job-detail-form',
    components: { vText, vField, vTable, pDetailButtons, pPickerPath, pPickerRange, pPickerVehicle }, //eslint-disable-line
    props: {
        id: String,
        ids: Array,
        value: Object,
        status: String,
        compact: Boolean,
        readonly: Boolean
    },
    data () {
        return {
            activeNames: ['1','2','3','4','5'],
            form: {},
            rules: {
                id: [{ required: true, message: $t('lang.id') + ' ' + $t('lang.required'), trigger: 'blur' }]
            },
            endEventOptions: Object.keys(JOB_END_EVENTS),
            modeOptions: Object.keys(JOB_MODES),
            propertiesColumns: [
                { label: 'name', prop: 'key', width: 180 },
                { label: 'value', prop: 'val', width: 120 }
            ],
            orderListColumns: [
                { label: 'icon icon-clock', prop: 'isAppointment', width: 30, isIcon: true, type: 'switch' },
                { label: 'location', prop: 'path', width: 120, type: 'pickerPath' },
                { label: 'range', prop: 'range', width: 120, type: 'pickerRange' },
                { label: 'action name', prop: 'actionCode', width: 125, type: 'select', default: -1 },
                { label: 'action value', prop: 'actionValue', width: 125, default: 0 }
            ],
            orderListOptions: {
                path: [],
                actionCode: []
            },
            progressBarStyle: { width: '0' }
        };
    },
    computed: {
        aptTimeDisabled() {
            return this.form.appointmentMode !== JOB_MODES.FIXED;
        }
    },
    watch: {
        ids() {
            // if (val && val.length > 0) this.init();
            this.init();
        },
        value: { handler (val) { this.form = val; }, deep: true },
        form (val) {
            this.$emit('input', val);
        },
        '$root.ws.serverTime'() {
            this.initAsync();
        },
        'form.vehicleKey'(val) {
            // TODO: change actions, when vehicle(model) changed.
            this.form.modelExt = Chef.getVehicleModelById(val, this.$root.resources.models);
            this.resetOrderListOptions();
        }
    },
    created() {
        bus.on(`jobsEditor.init`, this.init);
        bus.on(`jobsEditor.quickJob`, this.quickJob);
    },
    mounted() {
        this.init();
    },
    beforeDestroy() {
        bus.off(`jobsEditor.init`, this.init);
        bus.off(`jobsEditor.quickJob`, this.quickJob);
    },
    methods: {
        async init(local) {
            this.orderListOptions.path = this.getPathOptions();
            this.resetOrderListOptions();

            if ((local && Object.keys(local).length) || (this.local && Object.keys(this.local).length)) {
                if (local) this.local = local;
                Chef.extendJob(this.local);
                this.form = this.local;
            } else if (this.ids.length) {
                let res = await this.getDetails(this.ids);
                this.form = Chef.extendJob(res, this.$root.resources.models);
                this.resetOrderListOptions();
            } else {

            }
        },
        initAsync() {
            if (this.readonly) Chef.extendJobAsync(this.form, this.$root.resources.jobs);
            this.progressBarStyle.width = this.form.progressLabelExt + '%';
            this.progressBarStyle.background = this.form.progressColorExt;
        },
        async resetOrderListOptions() {
            this.orderListOptions.actionCode = await this.getActionsOptions();
        },
        async getActionsOptions() {
            let rtn = [ { label: 'NONE', value: -1 }, { label: 'STOP', value: 0 } ];
            if (this.form && this.form.modelExt && this.form.modelExt.actions) {
                rtn = [];
                Object.keys(this.form.modelExt.actions).forEach(v => {
                    rtn.push({ label: v, value: this.form.modelExt.actions[v].code });
                });
            } else if (this.form && this.form.vehicleKey) {
                let res = await API.getLocalResources('models');
                if (!res.list || !res.list.length) return rtn;
                // let m = res.list.find(v => new RegExp('^' + v.vehicleKey).test(this.form.vehicleKey));
                // // let m = res.find(v => v.vehicleKey === this.form.vehicleKey);
                let m = Chef.getVehicleModelById(this.form.vehicleKey, res.list);
                // console.log('p-job-detail-form.getActionsOptions: ', this.form.vehicleKey, m, rtn);
                if (!m) return rtn;
                rtn = [];
                Object.keys(m.actions).forEach(v => {
                    rtn.push({ label: v, value: m.actions[v].code });
                });
            }
            return rtn;
        },
        getPathOptions() {
            return Chef.getPathsOptions(this.$root.resources.paths || []);
        },
        getOrderPreviewIcon(i) {
            return this.form.orderIndex == i ? 'icon icon-selected ' + this.form.jobStatusColorExt : 'icon icon-select';
        },
        getOrderPreviewText(o) {
            return `${$t('lang.location')}: ${o.path}, ${$t('lang.actions')}: ${o.actionCode}, ${$t('lang.value')}: ${o.actionValue}`;
        },

        getDetails(ids) {
            return API.filterLocalResources('jobs', ids).then(res => Chef.combineJobs(res.list));
        },

        quickJob(res) {
            console.log('p-job-detail-form.quickJob: ', res);
            this.$store.commit(enums.DESELECT_JOBS_ALL, [-1]);
            this.form = res;
        },
        validate(vehicleErrors = false) {
            if (vehicleErrors) {
                this.$refs.vTable.$children.concat().map(o => o.$el.classList.remove('error'));
                Object.keys(this.$validation).forEach(k => {
                    if (Object.keys(this.$validation[k]).length) {
                        let e = this.$refs.vTable.$children.concat().find(c => c._uid === parseInt(k));
                        e.$el.classList.add('error');
                    }
                });
            }
            for (let key in this.$validation) {
                if (this.$validation.hasOwnProperty(key)) {
                    for (let k in this.$validation[key]) {
                        if (this.$validation[key].hasOwnProperty(k)) {
                            this.$toast(this.$validation[key][k]);
                            return false;
                        }
                    }
                }
            }
            return true;
        },
        submit(e) {
            // v-table 里面没有必填项 所以this.validate无需校验了
            // if (!this.validate(true)) return Promise.reject('');
            return this.$refs.form.validate().then(valid => {
                if (valid) {
                    let form = Chef.shakeJob(this.form);
                    return API.updateJob(form, e.target || e.srcElement).then(res => {
                        if (this.local && Object.keys(this.local).length) this.local = null;
                        console.log('p-job-detail-form.submit.success: ', res);
                        bus.emit('p-table.init');
                        this.$store.commit(enums.DESELECT_JOBS_ALL);
                        // if (this.compact) bus.emit('p-panel.editEnableChange', false);
                        if (this.compact) {
                            bus.emit('p-panel.editEnableChange', false);
                            bus.emit('jobs.toggleRowSelection', []);
                        }
                    });
                } else {
                    let msg = $t('lang.submitError');
                    this.$message.error(msg);
                    return Promise.reject(msg);
                }
            });
        }
    }
};
</script>

<style lang="scss">
.p-job-detail-form {
    .progress {
        position: relative;
        width: 62%;
        height: 18px;
        border: #999999 1px solid;
        border-radius: 3px;

        .v-text {
            text-align: center;
            margin: 3px;
        }
    }
    .progressBar {
        position: absolute;
        height: 100%;
        top: 0;
        left: 0;
        z-index: 0;
        box-shadow: 3px 0 3px #ccc;
        border-radius: 3px;
    }
    .genral-box {
        .el-collapse-item__content {
            flex-direction: column !important;
            .el-form-item {
                width: 100%;
                flex-direction: row;
                justify-content: space-between;
                .p-picker-vehicle {
                    width: 240px;
                    .el-input {
                        width: 205px;
                    }
                }
                .el-select--mini {
                    width: 240px;
                    .el-input {
                        width: 205px;
                    }
                }
            }

            .el-date-editor {
                width: 240px;
                .el-input__inner {
                    width: 205px;
                    background: #fff;
                }
            }
        }
        &.readonle {
            .el-collapse-item__content {
                flex-direction: column !important;
                .el-form-item {
                    width: 100%;
                    flex-direction: row;
                    justify-content: space-between;
                    .el-form-item__content {
                        width: 240px;
                    }
                }
            }
        }
    }
    .styleLabel {
        .el-form-item__content {
            width: 240px !important;
            .el-input--mini {
                width: 203px;
            }
        }
    }
}
</style>
